package snail.controllers;

import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import snail.config.Configuration;
import snail.hibernate.util.HibernateUtil;
import snail.model.User;
import snail.misc.*;

public class RegisterFormController extends SimpleFormController {

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView mav = new PreparedModelAndView(request);
        ModelAndView mv = super.handleRequestInternal(request, response);
        if (mv != null) {
            mv.addAllObjects(mav.getModelMap());
            mv.setViewName("user/registerForm");
        }
        return mv;
    }

    @Override
    protected ModelAndView onSubmit(
            HttpServletRequest request,
            HttpServletResponse response,
            Object command,
            BindException errors) throws Exception {

        Session session = HibernateUtil.getSessionFactory().getCurrentSession();

        User user = (User) command;

        user.setPassword(Hash.sha256(user.getPassword()));
        session.save(user);

        
        request.getSession().setAttribute("registrationComplete", "true");




        Properties props = new Properties();
        props.put("mail.smtp.host", "mail.chalmers.se");
        props.put("mail.from", "mihkel@student.chalmers.se");
        javax.mail.Session mailSession = javax.mail.Session.getInstance(props, null);

        try {
            MimeMessage msg = new MimeMessage(mailSession);
            msg.setFrom();
            msg.setRecipients(Message.RecipientType.TO, user.getEmail());
            msg.setSubject("Hej");
            msg.setSentDate(new Date());

            String hash = Hash.sha1(user.getEmail());

            msg.setText("Tjena, " + user.getFirstName() + "!\n" +
                    "Gött mos ere att du reggat dej hos oss.. " +
                    "klicka på länken här nedan för att verifiera att det är du som registrerat dig...\n" +
                    Configuration.BASE_URL + "/user/verify?id=" + user.getUserId() + "&key=" + hash);

            Transport.send(msg);
        } catch (MessagingException mex) {
            System.out.println("send failed, exception: " + mex);
        }

        response.sendRedirect("registerComplete");

        return null;
    }
}
